<template>
  <div class="app-container">
    <!-- 用户介绍 -->
    <el-card class="box-card">
      <h3>用户编辑</h3>
      <el-form ref="users" :rules="rules" :model="users" label-width="150px">
        <el-form-item label="用户编号" prop="userId">
          <el-input v-model="users.userId" readonly/>
        </el-form-item>
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="users.username"/>
        </el-form-item>
        <el-form-item label="用户性别" prop="userSex">
          <el-select v-model="users.userSex">
            <el-option
              v-for="(item, index) in sexTypes"
              :key="index"
              :label="item.lable"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="用户图片">
          <el-upload
            ref="upload"
            :on-change="handleChangeFile"
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadPicUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img v-if="users.userImg" :src="users.userImg" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 更新取消按钮 -->
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleEdit">更新用户</el-button>
    </div>
  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import {detailGoods, editGoods, listCatAndBrand} from "@/api/goods/goods";
import {createStorage, uploadPath} from "@/api/system/storage";
import {getByIdUser, editUsers} from "@/api/user";
import Editor from "@/components/TEditor.vue";
import {MessageBox} from "element-ui";
import {getToken} from "@/utils/auth";

export default {
  name: "usersEdit",
  components: {Editor},
  data() {
    return {
      sexTypes: [
        {label: 1, value: "女"},
        {label: 1, value: "男"},
      ],
      uploadPath: process.env.VUE_APP_TARGET_API + "/upload", // 图片上传路径
      users: {gallery: []}, // 用户信息
      // 表单验证规则
      rules: {
        userId: [
          {required: true, message: "用户编号不能为空", trigger: "blur"},
        ],
        // username: [
        //   { required: true, message: "用户名称不能为空", trigger: "blur" },
        // ],
      },
      // 富文本编辑器初始化
      editorInit: {
        language: "zh_CN",
        convert_urls: false,
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount",
        ],
        toolbar: [
          "searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample",
          "hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen",
        ],
        // 上传钩子
        images_upload_handler: function (blobInfo, success, failure) {
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          createStorage(formData)
            .then((res) => {
              success(res.data.data.url);
            })
            .catch(() => {
              failure("上传失败，请重新上传");
            });
        },
      },
    };
  },
  computed: {
    // 上传请求头
    headers() {
      return {
        "Shopping-Admin-Token": getToken(),
      };
    },
  },

  created() {
    // 页面数据初始化
    this.init();
  },
  methods: {
    handleChangeFile(file, fileList) {
      if (!file) return;
      // suffix：文件的后缀名
      var suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const limit = file.size / 1024 < 50;
      if (suffix !== "jpg" && suffix !== "png" && suffix !== "bmp") {
        this.$refs.upload.clearFiles();
        this.$message({
          message: "上传文件只能是 .jpg、.png、bmp格式!",
          type: "warning",
        });
        return false;
      }
      if (!limit) {
        this.$refs.upload.clearFiles();
        this.$message({
          message: "上传文件大小必须小于 50KB!",
          type: "warning",
        });
        return false;
      }
    },

    // 获取数据 ，判断是否有用户id传入
    init: function () {
      if (this.$route.query.id == null) {
        return;
      }
      const usersId = this.$route.query.id;
      getByIdUser(usersId).then((response) => {
        this.users = response.data;
      });
    },
    handleCancel() {
      this.$router.push({path: "/system/user"});
    },
    // 更新用户钩子
    handleEdit: function () {
      // 构建提交数据
      const finalusers = {
        userId: this.users.userId,
        userImg: this.users.userImg,
        username: this.users.username,
        userSex: this.users.userSex,
      };
      console.log(this.users);
      // 调用接口
      editUsers(finalusers)
        .then((response) => {
          console.log(222222222);
          console.log(response);
          this.$notify.success({
            title: "成功",
            message: "创建成功",
          });
          this.init();
          this.$router.push({path: "/system/user"});
        })
        .catch((response) => {
          MessageBox.alert("业务错误：" + response.data.errmsg, "警告", {
            confirmButtonText: "确定",
            type: "error",
          });
        });
    },

    // 获取图片上传路径
    uploadPicUrl: function (response) {
      let fm = process.env.VUE_APP_IMAGE_SHOW_FORM;
      if ("db" == fm) {
        this.users.userImg = response.data.url;
      } else if ("file" == fm) {
        this.users.userImg = process.env.VUE_APP_TARGET_API + response.data.url;
      }
    },
    // 限制上文件个数
    uploadOverrun: function () {
      this.$message({
        type: "error",
        message: "上传文件个数超出限制!最多上传5张图片!",
      });
    },
    // 获取图片路径
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.users.gallery.push(response.data.url);
      }
    },

    // 上传成功钩子
    uploadProductUrl: function (response) {
      this.productForm.url = response.data.url;
    },
  },
};
</script>
